<script setup lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import type { Action } from "element-plus";
import { ref, onMounted } from "vue";

import dateDisplay from "../../components/date-display/index.vue";
import images from "../../components/images/index.vue";
import cropper from "../../components/cropper/index.vue";

const electron = window["electron"];
const wsPath = "ws://127.0.0.1:8888";
let websocket = new WebSocket(wsPath);
const photographValue = ref("2");
const homeData = ref({
  tabsFlag: true,
  showPhoto: "",
  cropperPhoto: "",
  templePhoto: "",
  productName: "KB05",
  delayElimination: 1500,
  outputHold: 500,
  exposureTime: 100,
  sharpnessMode: 1,
  sharpness: 1.5,
  yieldCount: 0,
  falseCount: 0,
  yieldRate: 0,
  falseRate: 0,
  totalCount: 0,
  isShowCropper: false,
  portName: "未连接",
  positioningTemplate: "",
  glueHorizontalEdge: "",
  lowerAdhesiveHorizontalEdge: "",
  darkGlueHorizontalEdge: "",
  brightGlueExceedsTheArea: "",
  darkGlueExceedsTheArea: "",
  indentationTemplateArea: "",
  indentationTemplateArea2: "",
});
const photographOptions = [
  {
    value: "1",
    label: "一次拍照",
  },
  {
    value: "2",
    label: "二次拍照",
  },
  {
    value: "3",
    label: "三次拍照",
  },
  {
    value: "4",
    label: "四次拍照",
  },
  {
    value: "5",
    label: "五次拍照",
  },
];

const tabsFlagChange = (value) => {
  homeData.value.tabsFlag = value;
};

const websocketSend = (data) => {
  if (websocket.readyState === 1) {
    console.log(data);
    websocket.send(data);
  }
};

const createWebSocket = () => {
  websocket = new WebSocket(wsPath);

  websocket.onopen = () => {
    const data = JSON.stringify({
      cmd: "hello",
    });

    websocketSend(data);
  };

  websocket.onmessage = (event) => {
    const data = JSON.parse(event.data);

    switch (data.cmd) {
      case "123":
        setPortName();
        showTemplePhoto(data);
        break;
      case "show_toast":
        showToast(data);
        break;
      case "show_photo":
        showPhoto(data);
        break;
      case "show_camera_info":
        showCameraInfo(data);
        break;
      case "show_photo_collect":
        showPhotoCollect(data);
        break;
      case "show_template_photo":
        showTemplePhoto(data);
        break;
    }
  };

  websocket.onerror = (error) => {
    ElMessage(`错误提示: ${JSON.stringify(error)}`);
  };

  websocket.onclose = () => {
    ElMessage("连接已经断开，准备重新连接");
    electron.serialPortClose();
    createWebSocket();
  };
};

const setPortName = () => {
  electron.onSerialPortDataCatch(takePhoto);
  electron.serialPortList();
};

const showToast = (data) => {
  ElMessageBox.alert(data.message, "错误提示", {
    confirmButtonText: "确认",
    callback: (action: Action) => { },
  });
};

const setCameraInfo = () => {
  const data = JSON.stringify({
    cmd: "set_camera_info",
    message: {
      exposureTime: homeData.value.exposureTime,
      sharpnessMode: homeData.value.sharpnessMode,
      sharpness: homeData.value.sharpness,
    },
  });

  websocketSend(data);
};

const showCameraInfo = (data) => {
  homeData.value.exposureTime = data.message.exposureTime;
  homeData.value.sharpnessMode = data.message.sharpnessMode;
  homeData.value.sharpness = data.message.sharpness;
};

const takePhoto = (portName) => {
  homeData.value.portName = portName;

  const data = JSON.stringify({
    cmd: "take_photo",
  });

  websocketSend(data);
};

const showPhoto = (data) => {
  homeData.value.showPhoto = data.message;
  homeData.value.yieldCount = data.Yield_Count;
  homeData.value.falseCount = data.False_Count;
  homeData.value.yieldRate = data.Yield_Rate;
  homeData.value.falseRate = data.False_Rate;
  homeData.value.totalCount = data.Total_Count;
};

const takePhotoCollect = () => {
  const data = JSON.stringify({
    cmd: "take_photo_collect",
  });

  websocketSend(data);
};

const showPhotoCollect = (data) => {
  homeData.value.cropperPhoto = `data:image/png;base64,${data.message}`;
  homeData.value.isShowCropper = true;
};

const saveTemplatePhoto = (base64) => {
  const newBase64 = base64.replace("data:image/jpeg;base64,", "");
  const data = JSON.stringify({
    cmd: "save_template_photo",
    message: newBase64,
  });

  websocketSend(data);
};

const showTemplePhoto = (data) => {
  homeData.value.templePhoto = data.message;
};

const quitSoftware = () => {
  ElMessageBox.confirm("确认要退出软件?", "注意", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    electron.quitAppRequest();
  });
};

const handleCropperNotified = (base64) => {
  homeData.value.isShowCropper = false;
  saveTemplatePhoto(base64);
};

onMounted(() => {
  createWebSocket();
});
</script>

<template>
  <div class="container">
    <div class="header">
      <div class="top-logo"></div>
      <div class="top-tab-box">
        <!-- <div class="top-tab-item" @click="tabsFlagChange(true)">
          <div class="top-tab-bg" :class="{ active: homeData.tabsFlag }"></div>
          <i class="top-tab-icon main" :class="{ active: homeData.tabsFlag }"></i>
          <div class="top-tab-text" :class="{ active: homeData.tabsFlag }">主显示</div>
        </div>
        <div class="top-tab-item" @click="tabsFlagChange(false)">
          <div class="top-tab-bg" :class="{ active: !homeData.tabsFlag }"></div>
          <i class="top-tab-icon collection" :class="{ active: !homeData.tabsFlag }"></i>
          <div class="top-tab-text" :class="{ active: !homeData.tabsFlag }">采集</div>
        </div> -->
      </div>
      <dateDisplay />
    </div>

    <div class="camera-box" v-show="homeData.tabsFlag">
      <div class="camera-image">
        <div class="camera-title">一次拍照</div>
        <images :imgUrl="homeData.showPhoto" />
      </div>

      <div class="operation-box">
        <!-- <div class="operation-item">
          <div class="operation-input-box">
            <div class="operation-text">产品名称</div>
            <input
              class="operation-input long"
              v-model="homeData.productName"
              placeholder="产品名称"
            />
          </div>
          <div class="operation-button-box">
            <button class="operation-button save">保存</button>
            <button class="operation-button open">打开</button>
          </div>
        </div> -->
        <div class="operation-item">
          <div class="operation-input-box">
            <div class="operation-text">曝光时间</div>
            <input class="operation-input long" v-model="homeData.exposureTime" maxlength="5" placeholder="曝光时间" />
          </div>
          <div class="operation-input-box">
            <div class="operation-text">锐化程度</div>
            <input class="operation-input long" v-model="homeData.sharpness" maxlength="3" placeholder="锐化程度" />
          </div>
          <div class="operation-input-box">
            <div class="operation-text">锐化模式</div>
            <el-radio-group v-model="homeData.sharpnessMode">
              <el-radio :value="1">开启</el-radio>
              <el-radio :value="0">关闭</el-radio>
            </el-radio-group>
          </div>
          <div class="operation-button-box">
            <button class="operation-button long" @click="setCameraInfo()">
              设置参数
            </button>
          </div>
          <div>当前模板</div>
          <div class="temple-photo">
            <images :imgUrl="homeData.templePhoto" />
          </div>
          <div class="operation-button-box">
            <button class="operation-button long" @click="takePhotoCollect()">
              保存截图
            </button>
          </div>
          <!-- <div class="operation-input-box">
            <div class="operation-text">延时剔除</div>
            <input
              class="operation-input long"
              v-model="homeData.delayElimination"
              placeholder="延时剔除"
            />
          </div>
          <div class="operation-input-box">
            <div class="operation-text">输出保持</div>
            <input
              class="operation-input long"
              v-model="homeData.outputHold"
              placeholder="输出保持"
            />
          </div> -->
          <!-- <div class="operation-button-box">
            <button class="operation-button long" @click="takePhoto()">测试剔除开</button>
          </div> -->
          <div class="operation-input-box">
            <div class="operation-text">良品数</div>
            <div class="operation-text black">{{ homeData.yieldCount }}</div>
          </div>
          <div class="operation-input-box">
            <div class="operation-text">良品率</div>
            <div class="operation-text black">{{ homeData.yieldRate }}%</div>
          </div>
          <div class="operation-input-box">
            <div class="operation-text">不良品数</div>
            <div class="operation-text black">{{ homeData.falseCount }}</div>
          </div>
          <div class="operation-input-box">
            <div class="operation-text">不良品率</div>
            <div class="operation-text black">{{ homeData.falseRate }}%</div>
          </div>
          <div class="operation-button-box">
            <div class="operation-text">识别总数</div>
            <div class="operation-text black" v-show="homeData.totalCount > 0">
              {{ homeData.totalCount }}
            </div>
            <button class="operation-button long2" v-show="homeData.totalCount === 0">
              识别中
            </button>
          </div>
          <div class="operation-input-box">
            <div class="operation-text">连接串口:</div>
            <div class="operation-text black">{{ homeData.portName }}</div>
          </div>
          <div class="operation-button-box">
            <button class="operation-button out" @click="quitSoftware()">
              退出软件
            </button>
          </div>
        </div>
      </div>
    </div>

    <div class="camera-box" v-show="!homeData.tabsFlag">
      <div class="camera-image">
        <div class="camera-title">图像展示</div>
        <images :imgUrl="homeData.showPhoto" />
      </div>

      <div class="operation-box">
        <div class="operation-item">
          <div class="operation-input-box">
            <div class="operation-text">曝光时间</div>
            <input class="operation-input time" v-model="homeData.exposureTime" placeholder="曝光时间" />
            <button class="operation-button short">实况采集</button>
          </div>
          <div>采集的本地图片路径：</div>
          <div class="operation-input-box">C\Users\aa\AppData\Local\Tem</div>
          <div class="operation-input-box">
            <el-select v-model="photographValue" placeholder="Select" style="width: 120px">
              <el-option v-for="item in photographOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <div class="operation-input-box">
            <input class="operation-input long" v-model="homeData.positioningTemplate" placeholder="定位模板区域" />
            <button class="operation-button short">创建</button>
          </div>
          <div class="operation-input-box">
            <div class="operation-colour">
              <div class="red"></div>
            </div>
            <input class="operation-input short" v-model="homeData.glueHorizontalEdge" placeholder="上胶横边（明到暗）" />
            <button class="operation-button short">写入</button>
          </div>
          <div class="operation-input-box">
            <div class="operation-colour">
              <div class="black"></div>
            </div>
            <input class="operation-input short" v-model="homeData.lowerAdhesiveHorizontalEdge"
              placeholder="下胶横边（明到暗）" />
            <button class="operation-button short">写入</button>
          </div>
          <div class="operation-input-box">
            <div class="operation-colour">
              <div class="black"></div>
            </div>
            <input class="operation-input short" v-model="homeData.darkGlueHorizontalEdge" placeholder="暗胶横边（暗到明）" />
            <button class="operation-button short">写入</button>
          </div>
          <div class="operation-input-box">
            <div class="operation-colour">
              <div class="black"></div>
            </div>
            <input class="operation-input short" v-model="homeData.brightGlueExceedsTheArea" placeholder="亮胶超出区域" />
            <button class="operation-button short">写入</button>
          </div>
          <div class="operation-input-box">
            <div class="operation-colour none"></div>
            <input class="operation-input short" v-model="homeData.darkGlueExceedsTheArea" placeholder="暗胶超出区域" />
            <button class="operation-button short">写入</button>
          </div>
          <div class="operation-input-box">
            <div class="operation-colour">
              <div class="black"></div>
            </div>
            <input class="operation-input short" v-model="homeData.indentationTemplateArea" placeholder="压痕1模板区域" />
            <button class="operation-button short">创建</button>
          </div>
          <div class="operation-input-box">
            <div class="operation-colour none"></div>
            <input class="operation-input short" v-model="homeData.indentationTemplateArea2" placeholder="压痕2模板区域" />
            <button class="operation-button short">创建</button>
          </div>
        </div>
      </div>
    </div>
  </div>
  <el-dialog v-model="homeData.isShowCropper">
    <cropper :imgUrl="homeData.cropperPhoto" @cropperNotified="handleCropperNotified" />
  </el-dialog>
</template>

<style>
.container {
  min-height: 100vh;
  height: 100%;
  background: #ebebf3;
}

.header {
  background: url("../../assets/images/header.png") no-repeat;
  background-size: 100% 100%;
  height: 103px;
  display: flex;
}

.top-logo {
  width: 275px;
  height: 52px;
  background: url("../../assets/images/logo.png") no-repeat;
  margin: 27px 0 0 38px;
}

.top-tab-box {
  flex: 1;
  display: flex;
  padding: 20px 0 0 10vw;
}

.top-tab-item {
  margin-right: 50px;
  cursor: pointer;
  position: relative;
}

.top-tab-bg {
  width: 50px;
  height: 50px;
  background: #ffffff;
  border-radius: 90px;
  margin-bottom: 4px;
  opacity: 0.3;
}

.top-tab-bg.active {
  opacity: 1;
}

.top-tab-icon {
  width: 50px;
  height: 50px;
  display: block;
  position: absolute;
  top: 0;
  left: 0;
}

.top-tab-icon.main {
  background: url("../../assets/images/icon-01.png") no-repeat center center;
}

.top-tab-icon.main.active {
  background: url("../../assets/images/icon-02.png") no-repeat center center;
}

.top-tab-icon.collection {
  background: url("../../assets/images/icon-03.png") no-repeat center center;
}

.top-tab-icon.collection.active {
  background: url("../../assets/images/icon-04.png") no-repeat center center;
}

.top-tab-text {
  font-size: 16px;
  color: #ffffff;
  text-align: center;
  opacity: 0.7;
}

.top-tab-text.active {
  opacity: 1;
}

.camera-box {
  display: flex;
}

.camera-image {
  flex: 2;
  padding: 30px;
}

.camera-title {
  height: 42px;
  line-height: 42px;
  font-size: 20px;
  color: #fff;
  background: url("../../assets/images/title.png") no-repeat left center;
  border-bottom: #37ada7 solid 1px;
  padding-left: 20px;
  margin-bottom: 10px;
}

.temple-photo {
  width: 334px;
  margin-bottom: 20px;
}

.el-radio__input.is-checked+.el-radio__label {
  color: #5a5e5d !important;
}

.el-radio__input.is-checked .el-radio__inner {
  background: #28a7a0;
  border-color: #28a7a0;
}
</style>
